package cn.edu.dlmu.cogo.register;

import cn.edu.dlmu.cogo.framework.annotation.Priority;
import cn.edu.dlmu.cogo.framework.config.JavaConfig;
import cn.edu.dlmu.cogo.framework.config.WebConfig;
import cn.edu.dlmu.cogo.framework.context.ApplicationContext;
import cn.edu.dlmu.cogo.framework.context.ApplicationContextAware;
import cn.edu.dlmu.cogo.framework.context.Level;
import cn.edu.dlmu.cogo.framework.utils.CogoClassUtil;
import cn.edu.dlmu.cogo.framework.web.CogoWebServerAware;
import cn.edu.dlmu.cogo.framework.web.WebServer;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;


/**
 * @author hongda.li@hand-china.com 2022/3/11 10:02
 */
@Priority(Level.Middle)
public class RegisterServerAware implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {

        // 判断是否开启了注册中心服务端
        boolean enableRegisterServer = CogoClassUtil.mainClassWithAnnotation(EnableRegisterServer.class);
        if (!enableRegisterServer) {
            applicationContext.removeBean(CogoRegisterController.class);
            applicationContext.removeBean(CogoRegisterCenter.class);
            return;
        }

        // 设置默认的注册中心配置类，如果在容器中存在配置类则优先获取
        JavaConfig.setConfig(new RegisterConfig());
        WebConfig webConfig = new WebConfig();
        RegisterConfig registerConfig = JavaConfig.getConfig(RegisterConfig.class);

        // 配置WebConfig类
        createWebRoot();
        webConfig.setPort(registerConfig.getPort());
        webConfig.setRoot(RegisterConstant.REGISTER_WEB_ROOT);
        webConfig.setRequestBody(new CogoWebServerAware().initRequestBody());

        // 更新容器中最新的WebConfig类和RegisterConfig类
        applicationContext.removeBean(WebConfig.class);
        applicationContext.setBean(webConfig);

        // 启动服务器
        new WebServer().startServer();

        // 启动线程监听续约请求
        CogoRegisterCenter center = (CogoRegisterCenter)applicationContext.getBean(CogoRegisterCenter.class);
        ThreadUtil.execute(() -> {
            //noinspection InfiniteLoopStatement
            while (true){
                for (ServiceInstance instance : center.getServiceList()) {
                    if (instance.getInterval() > registerConfig.getTimeToLive() + registerConfig.getBufferTime()) {
                        center.removeService(instance.getServiceName());
                        Console.error("[CogoRegisterServer]服务续租时间超时，已被自动下线[" + instance.getServiceName() + "]");
                    }
                }
            }
        });
    }

    private void createWebRoot(){
        new FileWriter(RegisterConstant.REGISTER_WEB_ROOT_HTML).writeFromStream(ResourceUtil.getStream(RegisterConstant.REGISTER_RESOURCE));
    }
}
